package com.dave.getaway.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.dave.getaway.app.common.util.Constants;
import com.dave.getaway.app.common.util.ConvertUtil;
import com.dave.getaway.app.model.MetaData;
import com.dave.getaway.app.model.Provider;
import com.dave.getaway.app.service.AbstractService;
import com.dave.getaway.app.service.ProviderService;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * @author wangwj
 * @version 1.0
 * @date 2021/12/18
 * @description: TODO
 */

@Service
public class ProviderServiceImpl extends AbstractService implements ProviderService {


    @Override
    public List<Provider> getServiceDTOS() {
        List<Provider> providers = new ArrayList<>();
        ConcurrentMap<String, Map<String, URL>> providerUrls = getRegistryCache().getOrDefault(Constants.PROVIDERS_CATEGORY,new ConcurrentHashMap<>());
        providerUrls.keySet().forEach(x -> {
            Map<String, URL> map = providerUrls.get(x);
            Provider provider = new Provider();
            provider.setServiceName(x);
            map.keySet().forEach(k -> {
                URL url = map.get(k);
                provider.setApplication(url.getParameter(Constants.APPLICATION_KEY));
                providers.add(provider);
            });
        });


        providers.stream().forEach(x -> {
            Map<String, String> info = ConvertUtil.serviceName2Map(x.getServiceName());
            MetadataIdentifier identifier = new MetadataIdentifier(info.get(Constants.INTERFACE_KEY),
                    info.get(Constants.VERSION_KEY),
                    info.get(Constants.GROUP_KEY),
                    Constants.PROVIDER_SIDE,
                    x.getApplication());

            String metadata = this.getProviderMetaData(identifier);
            x.setMetaData(JSONUtil.toBean(metadata, MetaData.class));
            x.setMethods(ArrayUtil.toArray(x.getMetaData().getMethods().stream().map(o -> o.getName()).collect(Collectors.toList()),String.class));
        });

        return providers;
    }

    public String getProviderMetaData(MetadataIdentifier providerIdentifier) {
        return metaDataCollector.getProviderMetaData(providerIdentifier);
    }
}
